public class Solution {

    public static void main(String[] args) {
        System.out.println(convert("PAYPALISHIRING", 3));
    }

    public static String convert(String s, int numRows) {
        if (numRows == 1 || numRows > s.length()){
            return s;
        }

        // 用于存储每一行的字符
        StringBuilder[] sb = new StringBuilder[numRows];

        for (int i = 0; i < numRows; i++) {
            sb[i] = new StringBuilder();
        }

        int row = 0;
        // 标识方向 true 下 false 上 当前行数等于0或行数等于numRows-1时，需要改变方向
        boolean goDown = false;
        for (int i = 0; i < s.length(); i++) {
            if (row == 0 || row == numRows - 1){
                goDown = !goDown;
            }
            sb[row].append(s.charAt(i));
            if (goDown){
                row++;
            } else {
                row--;
            }
        }

        StringBuilder res = new StringBuilder();
        for (StringBuilder stringBuilder : sb) {
            res.append(stringBuilder);
        }

        return res.toString();
    }
}